<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="合同类型" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable>
          <el-option
            v-for="dict in dict.type.contract_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable>
          <el-option
            v-for="dict in dict.type.contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="contractCustomerName">
        <el-input
          v-model="queryParams.contractCustomerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="contractAssetName">
        <el-input
          v-model="queryParams.contractAssetName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同签订日期" prop="contractSigningDate">
        <el-date-picker clearable
          v-model="queryParams.contractSigningDate"
          type="date"
          style="width: 205px"
          value-format="yyyy-MM-dd"
          placeholder="请选择合同签订日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>

        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:contractInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:contractInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:contractInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:contractInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractInfoList" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" width="180"  align="center" prop="contractCode" />
      <el-table-column label="客户名称" width="220" show-overflow-tooltip align="center" prop="contractCustomerName" />
      <el-table-column label="关联资产名" align="center" prop="contractAssetName" />
      <el-table-column label="合同签订日期" width="180" align="center" prop="contractSigningDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.contractSigningDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同类型" width="140" align="center" prop="contractType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_type" :value="scope.row.contractType"/>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" width="140" align="center" prop="contractStatus">
        <template slot-scope="scope">
          <el-link><dict-tag :options="dict.type.contract_status" :value="scope.row.contractStatus"/></el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
              size="small"
              type="primary"
              title="修改"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            v-hasPermi="['business:contractInfo:edit']"
          ></el-button>
          <el-button
              size="small"
              type="danger"
              title="删除"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            v-hasPermi="['business:contractInfo:remove']"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" clearable style="width: 100%" placeholder="请选择合同类型">
                <el-option
                    v-for="dict in dict.type.contract_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产名称" prop="contractAssetId">
              <el-select v-model="form.contractAssetId" filterable @change="changeAsset"  clearable style="width: 100%" placeholder="请选择资产名称">
                <el-option
                    v-for="asset in assetList"
                    :key="asset.assetId"
                    :label="asset.assetName"
                    :value="asset.assetId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="contractCustomerId">
              <el-select v-model="form.contractCustomerId" filterable @change="changeCustomer" clearable style="width: 100%" placeholder="请选择客户名称">
                <el-option
                    v-for="customer in customerList"
                    :key="customer.customerId"
                    :label="customer.customerName"
                    :value="customer.customerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="签订日期" prop="contractSigningDate">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="form.contractSigningDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择签订日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="起止时间" prop="contractDate">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.contractDate"
                type="daterange"
                value-format="yyyy-MM-dd"
                @change="handleDateChange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="租金" prop="contractRent">
              <el-input v-model.number="form.contractRent" style="width: 100%" placeholder="请输入租金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="押金" prop="contractCashPledge">
              <el-input v-model.number="form.contractCashPledge" style="width: 100%" placeholder="请输入押金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付类型" prop="contractPaymentType">
              <el-select v-model="form.contractPaymentType" clearable style="width: 100%" placeholder="请选择支付类型">
                <el-option
                    v-for="dict in dict.type.pay_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="合同负责人" prop="managerId">
          <el-select v-model="form.managerId" clearable filterable placeholder="请选择合同负责人">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同备注" prop="contractRemark">
          <el-input v-model="form.contractRemark" type="textarea" clearable placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="合同文件" prop="contractUrl">
          <contractUploadTools @contractData="contractData" :limit="1" v-model="form.contractUrl" :fileType="['pdf']"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContractInfo, getContractInfo, delContractInfo, addContractInfo, updateContractInfo } from "@/api/business/contractInfo";
import { getAssetInfoList } from '@/api/business/assetInfo'
import { getCustomerInfoList } from '@/api/business/customerInfo'
import {getAllUserList} from "@/api/login";
import contractUploadTools from "@/components/FileUpload/contactindex";
export default {
  name: "ContractInfo",
  components: {
    contractUploadTools
  },
  dicts: ['contract_type', 'contract_status', 'pay_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      assetList: [],
      customerList: [],
      // 合同台账表格数据
      contractInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: null,
        contractType: null,
        contractAssetId: null,
        contractAssetName: null,
        contractCustomerId: null,
        contractCustomerName: null,
        contractSigningDate: null,
        contractStartDate: null,
        contractEndDate: null,
        contractRent: null,
        contractPaymentType: null,
        contractCashPledge: null,
        contractRemark: null,
        contractUrl: null,
        contractStatus: null,
        contractDate: null,
        contractIsDelete: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      userList: [],
      // 表单校验
      rules: {
        contractType: [
          { required: true, message: "请选择合同类型", trigger: "change" }
        ],
        contractAssetId: [
          { required: true, message: "请选择资产名称", trigger: "change" }
        ],
        contractCustomerId: [
          { required: true, message: "请选择客户名称", trigger: "change" }
        ],
        contractSigningDate: [
          { required: true, message: "签订日期不能为空", trigger: "blur" }
        ],
        contractDate: [
          { required: true, message: "起止时间不能为空", trigger: "blur" }
        ],
        contractRent: [
          { required: true, message: "租金不能为空", trigger: "blur" },
          { type: 'number', message: '请输入数字', trigger: 'change' },
          { validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback(new Error('租金必须大于 0'));
              } else {
                callback();
              }
            }, trigger: 'change'
          }
        ],
        contractPaymentType: [
          { required: true, message: "请选择支付类型", trigger: "change" }
        ],
        contractCashPledge: [
          { required: true, message: "押金不能为空", trigger: "blur" },
          { type: 'number', message: '请输入数字', trigger: 'change' },
          { validator: (rule, value, callback) => {
              if (value && value < 0) {
                callback(new Error('押金必须大于等于 0'));
              } else {
                callback();
              }
            }, trigger: 'change'
          }
        ],

      }
    };
  },
  created() {
    this.getAllUserList()
    this.getInfoData();
    this.getList();
  },
  mounted() {

  },
  methods: {
    contractData(data) {
      if(data.remark.includes('租赁')) {
        this.form.contractType = 0
      }
      if(data.contractCustomerName) {
        let s = this.customerList.filter(i => i.customerName == data.contractCustomerName)
        if(s.length > 0) {
          this.form.contractCustomerId = s[0].customerId;
          this.form.contractCustomerName = s[0].customerName;
        }
      }
      if(data.contractAssetName) {
        let s = this.assetList.filter(i => i.assetId == data.contractAssetName)
        if(s.length > 0) {
          this.form.contractAssetId = s[0].assetId;
          this.form.contractAssetName = s[0].assetName;
        }
      }
      this.form.contractStartDate = data.contractStartDate
      this.form.contractEndDate = data.contractEndDate
      this.form.contractRent = data.contractRent
      this.form.contractCashPledge = data.contractCashPledge
      this.form.contractDate = [data.contractStartDate, data.contractEndDate]
    },
    getAllUserList() {
      getAllUserList().then(r => {
        this.userList = r
      })
    },
    // 行点击
    handleRowClick(row, column, event) {
      if(column.label != '操作') {
        this.$router.push('/ContractLedger/contract-info/' + row.contractId)
      }
    },
    handleDateChange(val) {
      if(val.length > 0) {
        this.form.contractStartDate = val[0]
        this.form.contractEndDate = val[1]
      } else {
        this.form.contractStartDate = ''
        this.form.contractEndDate = ''
      }
    },
    getInfoData() {
      getAssetInfoList().then(r => {
        this.assetList = r.data
      })
      getCustomerInfoList().then(r => {
        this.customerList = r.data
      })
    },
    /** 查询合同台账列表 */
    getList() {
      this.loading = true;
      listContractInfo(this.queryParams).then(response => {
        this.contractInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeAsset(val) {
      if(val) {
        this.form.contractAssetName = this.assetList.find(i => i.assetId == val).assetName
      } else {
        this.form.contractAssetName = ''
      }
    },
    changeCustomer(val) {
      if(val) {
        this.form.contractCustomerName = this.customerList.find(i => i.customerId == val).customerName
      } else {
        this.form.contractCustomerName = ''
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractCode: null,
        contractType: null,
        contractAssetId: null,
        contractAssetName: null,
        contractCustomerId: null,
        contractCustomerName: null,
        contractSigningDate: null,
        contractStartDate: null,
        contractEndDate: null,
        contractRent: null,
        contractPaymentType: null,
        contractCashPledge: null,
        contractRemark: null,
        contractUrl: null,
        contractStatus: null,
        contractDate: null,
        contractIsDelete: null,
        delFlag: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        managerId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同台账";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const contractId = row.contractId || this.ids
      getContractInfo(contractId).then(response => {
        this.form = response.data;
        this.form.contractDate = [this.form.contractStartDate, this.form.contractEndDate]
        this.open = true;
        this.title = "修改合同台账";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        delete this.form.contractDate
        if (valid) {
          if (this.form.contractId != null) {
            updateContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同台账编号为"' + contractIds + '"的数据项？').then(function() {
        return delContractInfo(contractIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/contractInfo/export', {
        ...this.queryParams
      }, `contractInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
